/***** BEGIN LICENSE BLOCK *****
 * Version: CPL 1.0/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Common Public
 * License Version 1.0 (the "License"); you may not use this file
 * except in compliance with the License. You may obtain a copy of
 * the License at http://www.eclipse.org/legal/cpl-v10.html
 *
 * Software distributed under the License is distributed on an "AS
 * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
 * implied. See the License for the specific language governing
 * rights and limitations under the License.
 *
 * Copyright (C) 2007 Ola Bini <ola@ologix.com>
 * 
 * Alternatively, the contents of this file may be used under the terms of
 * either of the GNU General Public License Version 2 or later (the "GPL"),
 * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the CPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the CPL, the GPL or the LGPL.
 ***** END LICENSE BLOCK *****/
package asruby.runtime.methods {

import asruby.Ruby;
import asruby.exceptions.JumpException;
import asruby.lang.RubyArray;
import asruby.lang.RubyModule;
import asruby.parser.StaticScope;
import asruby.runtime.Arity;
import asruby.runtime.Block;
import asruby.runtime.DynamicScope;
import asruby.runtime.EventHook;
import asruby.runtime.Frame;
import asruby.runtime.IRubyObject;
import asruby.runtime.JumpTarget;
import asruby.runtime.ThreadContext;
import asruby.runtime.Visibility;
import asruby.yarv.InstructionSequence;
import asruby.yarv.YARVMachine;

/**
 * @author <a href="mailto:ola.bini@ki.se">Ola Bini</a>
 * @version $Revision: 1.2 $
 */
public class YARVMethod extends DynamicMethod implements JumpTarget {
    private  var iseq:InstructionSequence;
    private  var staticScope:StaticScope;
    private  var arity:Arity;

    public  function YARVMethod(implementationClass:RubyModule, iseq:InstructionSequence, staticScope:StaticScope, visibility:Visibility){
        super(implementationClass, visibility, new CallConfiguration());
        this.staticScope = staticScope;
        this.iseq = iseq;

        var opts: Boolean =  iseq.args_arg_opts > 0 || iseq.args_rest > 0;
        var req: Boolean =  iseq.args_argc > 0;
        if(!req && !opts) {
            this.arity = Arity.noArguments();
        } else if(req && !opts) {
            this.arity = Arity.fixed(iseq.args_argc);
        } else if(opts && !req) {
            this.arity = Arity.optional();
        } else {
            this.arity = Arity.required(iseq.args_argc);
        }
    }

    public override function call(context:ThreadContext, self:IRubyObject, klazz:RubyModule, name:String, args:Array, block:Block):IRubyObject{
    	//assert args != null;
        
        var runtime: Ruby =  context.getRuntime();
        
        callConfig.pre(context, self, klazz, getArity(), name, args, block, staticScope, this);
        
        try {
            prepareArguments(context, runtime, args);
            getArity().checkArity(runtime, args);

            if (runtime.hasEventHooks()) traceCall(context, runtime, name);

            var scope: DynamicScope =  context.getCurrentScope();
            
            // Why not setArgValues
            scope.setArgValues(args, args.length);

            return YARVMachine.INSTANCE.exec(context, self, iseq.body);
        } catch (rj:JumpException) {
        	if (rj.getTarget() == this) 
        		return IRubyObject( rj.getValue() );
       		throw rj;
        } 
        if (runtime.hasEventHooks()) traceReturn(context, runtime, name);
        callConfig.post(context);
        return null;
    }

    private  function prepareArguments(context:ThreadContext, runtime:Ruby, args:Array):void{
        context.setFile(iseq.filename);
        context.setLine(-1);

        var expectedArgsCount: int =  iseq.args_argc;
        var restArg: int =  iseq.args_rest;
        var hasOptArgs: Boolean =  iseq.args_arg_opts > 0;

        if (expectedArgsCount > args.length) {
            throw runtime.newArgumentError("Wrong # of arguments(" + args.length + " for " + expectedArgsCount + ")");
        }

        // optArgs and restArgs require more work, so isolate them and ArrayList creation here
        if (hasOptArgs || restArg != -1) {
            prepareOptOrRestArgs(context, runtime, args, expectedArgsCount, restArg, hasOptArgs);
        }
    }

    private  function prepareOptOrRestArgs(context:ThreadContext, runtime:Ruby, args:Array, expectedArgsCount:int, restArg:int, hasOptArgs:Boolean):Array{
        if (restArg == 0 && hasOptArgs) {
            var opt: int =  expectedArgsCount + iseq.args_arg_opts;

            if (opt < args.length) {
                throw runtime.newArgumentError("wrong # of arguments(" + args.length + " for " + opt + ")");
            }
        }
        
        var count: int =  expectedArgsCount + iseq.args_arg_opts + iseq.args_rest;

        var allArgs: Array =  new Array();
        
        // Combine static and optional args into a single list allArgs
        for ( var i:int = 0; i < count && i < args.length; i++) {
            allArgs.add(args[i]);
        }

        if (restArg != 0) {
            for ( var i:int = expectedArgsCount; i < args.length; i++) {
                allArgs.add(args[i]);
            }

            // only set in scope if named
            if (restArg >= 0) {
                var array: RubyArray =  runtime.newArray3(args.length - expectedArgsCount);
                for ( var i:int = expectedArgsCount; i < args.length; i++) {
                    array.append(args[i]);
                }

                context.getCurrentScope().setValue(restArg, array, 0);
            }
        }
        
        args = allArgs.toArray();
        return args;
    }
    
    private  function traceReturn(context:ThreadContext, runtime:Ruby, name:String):void{
        if (!runtime.hasEventHooks()) {
            return;
        }

        var frame: Frame =  context.getPreviousFrame();

        runtime.callEventHooks(context, EventHook.RUBY_EVENT_RETURN, frame.getFile(), frame.getLine(), name, getImplementationClass());
    }
    
    private  function traceCall(context:ThreadContext, runtime:Ruby, name:String):void{
        if (!runtime.hasEventHooks()) {
            return;
        }
        
        runtime.callEventHooks(context, EventHook.RUBY_EVENT_CALL, context.getFile(), context.getLine(), name, getImplementationClass());
    }
    
    public override  function getArity():Arity{
        return this.arity;
    }
    
    public override function dup():DynamicMethod{
        return new YARVMethod(getImplementationClass(), iseq, staticScope, getVisibility());
    }	
}// YARVMethod
}